#include "SpringMesh.h"

SpringMesh::SpringMesh()
{
}


SpringMesh::~SpringMesh()
{
}


SpringMesh* SpringMesh::GenerateSpringMesh()
{
	SpringMesh* sm = new SpringMesh();
	
	int numBalls = sm->numBalls;
	sm->numVertices = numBalls * numBalls;
	sm->vertices = new Vector3[sm->numVertices];
	sm->textureCoords = new Vector2[sm->numVertices];
	sm->colours = new Vector4[sm->numVertices];

	sm->numIndices = (numBalls - 1) * (numBalls - 1) * 6;
	sm->indices = new unsigned int[sm->numIndices];

	for (int i = 0; i < numBalls; i++)
	{
		for (int j = 0; j < numBalls; j++)
		{
			sm->vertices[i*numBalls + j] = sm->positions[i*numBalls + j];
			sm->textureCoords[i*numBalls + j] = Vector2(sm->positions[i*numBalls + j].x, sm->positions[i*numBalls + j].y);
			sm->colours[i*numBalls + j] = Vector4(1,1,0,0.5f);
		}
	}

	sm->type = GL_TRIANGLES;

	for (int i = 0; i < numBalls - 1; i++)
	{
		for (int j = 0; j < numBalls - 1; j++)
		{
			sm->indices[(i*(numBalls-1) + j) * 6] = i*numBalls + j;
			sm->indices[(i*(numBalls - 1) + j) * 6 + 1] = (i + 1)*numBalls + j;
			sm->indices[(i*(numBalls - 1) + j) * 6 + 2] = i*numBalls + j + 1;
			sm->indices[(i*(numBalls - 1) + j) * 6 + 3] = i*numBalls + j + 1;
			sm->indices[(i*(numBalls - 1) + j) * 6 + 4] = (i + 1)*numBalls + j;
			sm->indices[(i*(numBalls - 1) + j) * 6 + 5] = (i + 1)*numBalls + j + 1;
		}
	}
	sm->GenerateNormals();
	sm->GenerateTangents();
	sm->BufferData();

	return sm;
}


void SpringMesh::SpringMeshUpdate()
{
	for (int i = 0; i < numBalls; i++)
	{
		for (int j = 0; j < numBalls; j++)
		{
			vertices[i*numBalls + j] = positions[i*numBalls + j];
			textureCoords[i*numBalls + j] = Vector2(positions[i*numBalls + j].x, positions[i*numBalls + j].y);
			colours[i*numBalls + j] = Vector4(1, 1, 0, 0.5f);
		}
	}
}

void SpringMesh::Draw(bool update)
{
	SpringMeshUpdate();
	glDeleteBuffers(MAX_BUFFER, bufferObject);
	BufferData();
	
	if (update) {
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, texture);

		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, bumpTexture);
	}

	glBindVertexArray(arrayObject);
	if (bufferObject[INDEX_BUFFER]) {
		glDrawElements(type, numIndices, GL_UNSIGNED_INT, 0);
	}
	else{
		glDrawArrays(type, 0, numVertices);	//Draw the triangle!
	}
	glBindVertexArray(0);
}